<?php

namespace App\Http\Controllers\Admin\Author;
use App\Http\Requests\BooksPostRequest;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class BookController extends Controller
{
    public function getAdd()
    {
        //书籍添加页面
    	return view('admin.author.books.add');
    }

    public function getIndex(Request $request)
    {
        //获取登录作者的id
        $id = $request->session()->get('id');
        //查询作者的发布书籍
        $books = DB::table('hs_books')->where('aid','=',$id)->get();
        
        //作者书籍页面
    	return view('admin.author.books.index',['books'=>$books]);
    }

    public function postInsert(Request $request)
    {
    	//获取书名
        $data['b_name'] = $request->input('b_name');
        //获取书籍的描述
        $data['b_desc'] = $request->input('b_desc');
        //书籍的类型
        $data['b_cate'] = $request->input('type');
        //书籍的审核状态
        $data['status'] = 0;
        //获取书籍封面
        if($request->hasFile('pic')){
            $ext = $request->file('pic')->getClientOriginalExtension();
            $filename = time().str_random(5).'.'.$ext;
            $data['b_pic'] = '/uploads/books'.'/'.$filename;
            $request->file('pic')->move('./uploads/books/', $filename);
        }
        //获取是否免费
        $data['isfree'] = $request->input('isfree');
        //获取是否完结
        $data['isend'] = $request->input('isend');
        $data['aid'] = $request->session()->get('id');
        $res = DB::table('hs_books')->insert($data);
        //判断插入数据是否成功
        if($res){
            return back()->with('success','插入书籍成功');
        }else{
            return back()->with('error','插入书籍失败');
        }

        // echo '<img src="'.$data['pic'].'">';
    }

    public function getEdit($id)
    {
        $book = DB::table('hs_books')->where(['aid'=>1,'id'=>$id])->first();
        // dd($book);
        return view('admin.author.books.edit',['book'=>$book]);
    }

    public function postUpdate(Request $request)
    {
        $data['b_desc'] = $request->input('b_desc');
        $data['b_cate'] = $request->input('type');
        if($request->hasFile('pic')){
            $ext = $request->file('pic')->getClientOriginalExtension();
            $filename = time().str_random(5).'.'.$ext;
            // dd($filename);
            $data['b_pic'] = '/uploads/books'.'/'.$filename;
            $request->file('pic')->move('./uploads/books/', $filename);
        }
        $data['isfree'] = $request->input('isfree');
        $data['isend'] = $request->input('isend');
        $id = $request->input('id');
        $res = DB::table('hs_books')->where('id','=',$id)->update($data);
        //判断更新数据是否成功
        if($res){
            return redirect('/admin/books/index')->with('success','更新书籍成功');
        }else{
            return back()->with('error','更新书籍失败');
        }
        // dd($data);
    }
}
